// 1. 实现模块的容器
// 2. 依赖流入

let module = function () {
  //模块的容器
  let collections = {}
  return function (name, modules, action) {
    modules = modules.map((m) => collections[m])
    //将模块注册进模块容器
    collections[name] = action.call(null, ...modules)
  }
}.call()

module('Util', [], function (c) {
  return {
    total(data, field) {
      return data.reduce((sum, goods) => sum + goods[field], 0)
    },
    order(data, field, type = 'asc') {
      return data.sort((a, b) => {
        return type == 'asc' ? a[field] - b[field] : b[field] - a[field]
      })
    },
  }
})

class Cart {
  constructor(goods) {
    this.goods = goods
  }
  total() {
    let total
    module('Cart', ['Util'], (Util) => {
      total = Util.total(this.goods, 'price')
    })
    return total
  }
  order(field = 'price', type = 'asc') {
    let goods = []
    module('Cart', ['Util'], (Util) => {
      goods = Util.order(this.goods, field, type)
    })
    return goods
  }
}

const goods = [
  { name: 'IPAD', price: 199 },
  { name: 'ThinkPad Carbon X1', price: 9999 },
  { name: 'macbook Air m1', price: 7000 },
]

// Card@totla  获取商品总计
// Card@order

const cart = new Cart(goods)
console.log(cart.total())
console.table(cart.order('price', 'desc'))
